let initDetailFn = null //由分享卡片进入商品详情页时没有地址定位的回调函数，初始化商品详情页
let initDetailOption = {} //由分享卡片进入商品详情页时没有地址定位的回调函数的参数
import { queryCreditLines } from '@/api/payment';
import { getAccountTime, getAddress, getDiffCity, getWare } from '@/api/commonApi';
import { checkMemeberStatus } from '../api/payment';
import { Cookies } from '@/lib/js.cookie';
import {
  loginQueryMemberInfoV3
} from '@/api/login';
export const tdkUrl = { //tdk 项目  t4 https://m2-t4.xfs.com // 线上 https://m.xfs.com
  develop: 'https://m.xfs.com',
}
export const deepLinkkUrl = { //中间页
  develop: 'https://www.xfs.com',
}

export const showLoading = () => {
  // #ifdef MP-WEIXIN
  wx.showLoading({
    title: '加载中',
  })
  // #endif
  // #ifdef MP-ALIPAY
  my.showLoading({
    content: '加载中...',
    delay: 200,
  });
  // #endif
}
export const hideLoading = () => {
  // #ifdef MP-WEIXIN
  wx.hideLoading()
  // #endif
  // #ifdef MP-ALIPAY
  my.hideLoading();
  // #endif
}
/*获取可用额度*/
export const queryCreditLinesFn = async(params) => {
  const res = await queryCreditLines(params)
  if (res.errorCode == 0) {
    return res.data
  } else {
    uni.$u.toast('可用额度获取失败');
  }
}
/*判断当前账号是否是有效账号*/
export const checkMemeberStatusFn = async(params) => {
  let memeberStatus = false
  const res = await checkMemeberStatus(params)
  if (res.errorCode == 0) {
    memeberStatus = true
  } else if (res.errorCode == 6) {
    uni.$u.toast('登录已失效，请重新登录')
    clearCommonVuexState()
    uni.removeStorageSync('inviteCode');
    memeberStatus = false
  } else {
    uni.$u.toast('账号校验异常')
    clearCommonVuexState()
    memeberStatus = false
  }
  return memeberStatus
}
/*获取当前时间*/
export const getSystemTime = async() => {
  const res = await getAccountTime()
  if (res.errorCode == 0) {
    return res.data
  } else {
    uni.$u.toast('当前系统时间获取失败');
  }
}
/*格式化时间*/
export const formatDate = (date, format) => {
  let month = date.getMonth() + 1
  let day = date.getDate()
  if (month >= 1 && month <= 9) {
    month = '0' + month;
  }
  if (day >= 0 && day <= 9) {
    day = '0' + day;
  }
  const map = {
    mm: month,
    dd: day,
    yyyy: date.getFullYear()
  }
  return format.replace(/mm|dd|yyyy|yy/gi, matched => map[matched])
}
// 返回上一页或者多页
export const backPageRefresh = (page, params) => { // page这个值如果你只返回上一页可以不用传，返回上上页就传2，以此类推
  const pages = getCurrentPages(); // 当前页面
  let i = 0
  if (page) {
    i = page - 1
  }
  const beforePage = pages[pages.length - (2 + i)]; // 前一个页面或者更多  beforePage 这个值当你刷新浏览器后是无法返回的，需要用到浏览器历史记录返回上一页 history.back()
  for (const paramsKey in params) { //返回上一页或多页是设置参数
    beforePage.$vm[paramsKey] = params[paramsKey]
  }
  if (beforePage && beforePage.$vm.refreshRequest) {
    uni.navigateBack({
      delta: page || 1,
      success: function() {
        beforePage.$vm.refreshRequest(); // 执行前一个页面或者前几个页面并且刷新该页面
      }
    });
  } else {
    uni.navigateBack({
      delta: page || 1,
    });
  }
}
/*返回登录*/
export const returnLoginFn = (callbackUrl, urlParams) => {
  uni.redirectTo({
    url: `/login/login/codeLogin?callbackUrl=${callbackUrl}&urlParams=${urlParams}`
  })
}

/*获取高度*/
export const getNavHeight = () => {
  var TopHeight = ''
  // #ifdef MP-ALIPAY || MP-WEIXIN
  var statusBarHeight = uni.getSystemInfoSync().statusBarHeight
  // 获取微信胶囊的位置信息 width,height,top,right,left,bottom
  const custom = wx.getMenuButtonBoundingClientRect()
  // 导航栏高度(标题栏高度) = 胶囊高度 + (顶部距离 - 状态栏高度) * 2
  var navigationBarHeight = custom.height + (custom.top - statusBarHeight) * 2
  // 总体高度 = 状态栏高度 + 导航栏高度
  var navHeight = navigationBarHeight + statusBarHeight
  // 导航栏高度和搜索栏高度的和， rpx需要转化px 单位统一
  TopHeight = navHeight
  // #endif
  // #ifdef H5
  TopHeight = 44

  // #endif
  return TopHeight
}

/*设置错误页面函数*/
export const setPageParamsFn = (_this, pageType = null, title = '', showButton = true, methodName = 'testAgainFn', btnName = '重试') => {
  _this.pageParams.state = pageType
  _this.pageParams.emptyTitle = title
  _this.pageParams.errorTitle = title
  _this.pageParams.showButton = showButton
  _this.pageParams.methodName = methodName
  _this.pageParams.btnName = btnName
}
/*携带参数返回上一页面*/
export const navigateBackPrePage = (params) => {
  console.log('上级页面77', params)
  const pages = getCurrentPages()
  const prevPage = pages[pages.length - 2]
  for (const paramsKey in params) {
    prevPage.$vm[paramsKey] = params[paramsKey]
  }
  uni.navigateBack({ //返回
    delta: 1,
    //如果是购物车则刷新购物车页面
    success: function() {
      if (prevPage.route == 'purchaseOrder/index' || prevPage.route == 'myAccount/pointsMall/confirmExchange') {
        prevPage.$vm.reFresh();
      }
    }

  })
}
/*获取登录信息
 * /*memberInfo.status*
 * 账号状态 10：正常； 20：关闭； 30：注销
 * 账户类型：10:签约用户；20:普通用户;30认证用户;39普通会员-分销;40分销用户；
 */
export const getLoginInfoFn = (memberId) => {
  const params = { memberId: memberId }
  loginQueryMemberInfoV3(params).then((res) => {
    if (Number(res.code) != 0) {
      uni.$u.toast('获取用户信息失败')
      return
    }
    /**
   * 账号状态 10：正常； 20：关闭； 30：注销
    */
      // if(res.memberInfo.status !=10){
      //   uni.$u.toast('抱歉，此账号已注销或被关闭，请退出登录！')
      //   return
      // }
      // if (res.memberInfo.accountType == 30 && !res.crmCustomerInfos) { // 认证会员
      //   uni.$u.toast('抱歉，此账号暂未关联项目，请退出登录！')
      //   return
      // }  
    const vuex_lifeData = uni.getStorageSync('lifeData')
    uni.$u.vuex('vuex_allMemberInfos', res)
    uni.$u.vuex('vuex_memberInfo', res.memberInfo)
    uni.$u.vuex('vuex_memberCompanyInfo', res.memberCompanyInfo)
    uni.$u.vuex('vuex_crmCustomerInfos', res.crmCustomerInfos)
    uni.$u.vuex('vuex_memberLevelResp', res.memberLevelResp)
    uni.$u.vuex('vuex_mainCustomerSetupAndExtFront', res.mainCustomerSetupAndExtFront)
    const {
      loginAccount,
      mobilePhone,
      memberId
    } = res.memberInfo
    const {
      openid,
      unionid,
      userId
    } = res.authWechatInfo || {}
    // 微信支付宝登录完成之后vuex_accountInfo存在信息的取vuex_accountInfo中的值，其他登录方式不存在的取云采登录信息返回的值
    const curUserId = vuex_lifeData.vuex_accountInfo.userId || userId
    const curOpenid = vuex_lifeData.vuex_accountInfo.openid || openid
    const curUnionid = vuex_lifeData.vuex_accountInfo.unionid || unionid
    uni.$u.vuex('vuex_accountInfo', {
      loginAccount,
      mobilePhone,
      memberId,
      openid: curOpenid,
      unionid: curUnionid,
      userId: curUserId
    })
    // #ifdef H5
    Cookies.set('memberId', res.memberInfo.memberId, 365)
    Cookies.set('loginAccount', res.memberInfo.loginAccount, 365)
    Cookies.set('accountType', res.memberInfo.accountType, 365)
    Cookies.set('platformName', res.memberInfo.platformType, 365)
    Cookies.set('sourceUrl', encodeURIComponent(window.location.href), 1)
    Cookies.set('lgdomain', Cookies.getUrlDomain(), 365);
    Cookies.set('registerSource', res.memberInfo.registerSource, 365);
    const mySelectStation = JSON.parse(localStorage.getItem('my_select_station'));
    var lifeData = JSON.parse(localStorage.getItem('lifeData'))
    if (mySelectStation) {
      uni.$u.vuex('vuex_cityInfo', mySelectStation);
      uni.$u.vuex('vuex_nowAddress', { 'name': mySelectStation.cityName, 'cityCode': mySelectStation.cityCode, 'provinceCode': mySelectStation.provinceCode, 'provinceName': mySelectStation.provinceName, 'warehouseCode': mySelectStation.warehouseCode });
    } else {
      lifeData.data.vuex_nowAddress = {}
      lifeData.data.vuex_nowAddress.cityCode = '110100'
      lifeData.data.vuex_nowAddress.name = '北京市'
      lifeData.data.vuex_nowAddress.provinceCode = '110000'
      lifeData.data.vuex_nowAddress.provinceName = '北京市'
      lifeData.data.vuex_nowAddress.warehouseCode = '1'
      lifeData.data.vuex_cityInfo = {}
      lifeData.data.vuex_cityInfo.cityCode = '110100'
      lifeData.data.vuex_cityInfo.cityName = '北京市'
      lifeData.data.vuex_cityInfo.provinceCode = '110000'
      lifeData.data.vuex_cityInfo.provinceName = '北京市'
      lifeData.data.vuex_cityInfo.warehouseCode = '1'
      localStorage.setItem('lifeData', JSON.stringify(lifeData))
    }
    // #endif
  })
}
/*隐藏导航栏返回首页按钮*/
export const hideHomeBtn = () => {
  // #ifdef MP-WEIXIN
  wx.hideHomeButton()
  // #endif
  // #ifdef MP-ALIPAY
  my.hideBackHome()
  // #endif
}

// 清空vuex数据状态
export const clearCommonVuexState = () => {
  uni.$u.vuex('vuex_userInfo', {})
  uni.$u.vuex('vuex_accountInfo', {})
  uni.$u.vuex('vuex_loginStatus', false)
  uni.$u.vuex('vuex_token', '')
  uni.$u.vuex('vuex_memberInfo', {})
  uni.$u.vuex('vuex_memberLevelResp', {})
  uni.$u.vuex('vuex_crmCustomerInfos', [])
  uni.$u.vuex('vuex_memberCompanyInfo', {})
  uni.$u.vuex('vuex_cityInfo', {})
  uni.$u.vuex('vuex_sharePushmanCompanyInfo', {})
  uni.$u.vuex('vuex_alipay_qrcode', '')
  uni.$u.vuex('vuex_mainCustomerSetupAndExtFront', {})
  uni.$u.vuex('vuex_cityInfo_shopCar', {});
  uni.$u.vuex('vuex_cityInfo_shopCarClick', false);
}
/*获取platformType，平台类型*/
export const getPlatformTypeFn = (accountType) => {
  let platformType = ''
  switch (accountType) { // 账户类型：10:签约用户；20:普通用户;30认证用户;39普通会员-分销;40分销用户；
    case 10:
      platformType = 1
      break
    case 20:
      platformType = 2
      break
    case 30:
      platformType = 2
      break
    case 39:
      platformType = 3
      break
    case 40:
      platformType = 3
      break
    default:
      platformType = 2
      break
  }
  return platformType
}

// 阿里无痕验证
//#ifdef H5
export const initSlide = () => {
  setTimeout(() => {
    AWSC.use('nvc', function(state, module) {
      // 初始化 调用module.init进行初始化
      window.nvc = module.init({
        // 应用类型标识。它和使用场景标识（scene字段）一起决定了无痕验证的业务场景与后端对应使用的策略模型。您可以在阿里云验证码控制台的配置管理页签找到对应的appkey字段值，请务必正确填写。
        appkey: 'FFFF0N0000000000AB78',
        //使用场景标识。它和应用类型标识（appkey字段）一起决定了无痕验证的业务场景与后端对应使用的策略模型。您可以在阿里云验证码控制台的配置管理页签找到对应的scene值，请务必正确填写。
        scene: 'nvc_login_h5',
        // 二次验证获取人机信息串，跟随业务请求一起上传至业务服务器，由业务服务器进行验签。
        success: function(data) {
          console.log(data, '00000000000000000')
        },
        // 前端二次验证失败时触发该回调参数
        fail: function(failCode) {
          window.console && console.log(failCode)
        },
        // 前端二次验证加载异常时触发该回调参数。
        error: function(errorCode) {
          window.console && console.log(errorCode)
        }
      });
      // 绑定事件
    });
  })
}
// #endif
/*获取定位地址*/
const getDiffCityFn = (districtName, cityName) => { // 获取特殊城市
  const params = { type: 10 }
  getDiffCity(params).then((res) => {
    if (res.errorCode == 0) {
      // 特殊城市展示三级、不是特殊城市展示二级
      const Address = res.data.includes(cityName) ? districtName : cityName
      const params = {
        name: Address,
        level: res.data.includes(cityName) ? 103 : 102
      }
      getCityInfoFn(params)
    }
  })
}
const getAddressFn = (lat, lng) => { // 获取地址信息
  const params = { lat, lng }
  getAddress(params).then((res) => {
    const { districtName, cityName } = res.data
    uni.$u.vuex('vuex_mapAddress', res.data);
    if (res.errorCode == 0) {
      getDiffCityFn(districtName, cityName)
    }
  })
}
const getCityInfoFn = (params) => { // 根据name 和 level 获取某个地区的详细数据
  getWare(params).then((res) => {
    if (res.errorCode == 0) {
      var cityParams = {}
      const { grandpa_code, grandpa_name, parent_name, parent_code, name, code, warehouse_code, level } = res.data
      if (level == 102) {
        cityParams = {
          provinceCode: parent_code,
          provinceName: parent_name,
          cityCode: code,
          cityName: name,
          areaCode: '',
          areaName: '',
          warehouseCode: warehouse_code
        }
      } else if (level == 103) {
        cityParams = {
          provinceCode: grandpa_code,
          provinceName: grandpa_name,
          cityCode: parent_code,
          cityName: parent_name,
          areaCode: code,
          areaName: name,
          warehouseCode: warehouse_code
        }
      }
      uni.$u.vuex('vuex_nowAddress', res.data); // TODO 进入首页后获取位置授权，需要保存北京市的城市数据
      uni.$u.vuex('vuex_cityInfo', cityParams);
      initDetailFn(initDetailOption)
    }
  })
}
export const getLocationFn = (fn, option) => { // 初次获取定位
  initDetailFn = fn
  initDetailOption = option
  uni.getLocation({
    type: 'wgs84',
    success: (res) => {
      getAddressFn(res.latitude, res.longitude) // 经纬度获取定位信息
    },
    fail: () => {
      uni.$u.toast('拒绝授权');
      const params = {
        name: '北京市',
        level: 102
      }
      getCityInfoFn(params)
    }
  });
}

// 不能购买、添加、收藏校验
export const cannotActionGoodsValidate = (productType, accountType) => {
  const isNormalAccount = accountType == 20 // 普通用户
  const isCertifyAccount = accountType == 30 // 认证用户
  const validateMaps = {
    1: false, // 正常商品
    2: isNormalAccount || isCertifyAccount, // 临采商品-分为线索 潜在
    3: isNormalAccount || isCertifyAccount, // 供应商商品
    4: true, // 一物多码商品，
    6: isNormalAccount || isCertifyAccount, // 临采商品-分为线索 潜在
  }
  const cannotAction = validateMaps[productType] ?? false
  if (cannotAction) {
    uni.$u.toast('当前商品无法购买，可咨询在线客服！')
  }
  return cannotAction
}
